import React, { useState } from 'react';
import { Col, Form, Space, Input, Button, DatePicker } from 'antd';
import Icon from '@/components/layout/Icon';
import styles from './index.module.css';

const { RangePicker } = DatePicker;

const PlanItemBlock = (props) => {
  const { costTotal, formListName, decs, form, handleCost } = props;

  const handleOnBlur = () => {
    const data = form.getFieldValue(formListName);
    const count = data.reduce((total, cur) => {
      let t = total;
      if (cur && cur.costTime) {
        t += Number(cur.costTime);
      }
      return t;
    }, 0);
    handleCost(count);
  };

  return (
    <>
      <Col span={24}>
        <Form.List name={formListName}>
          {(fields, { add, remove }) => (
            <>
              <div style={{ marginBottom: 30 }}>
                {decs} （总计：{costTotal}h）
                <Button type="link" onClick={() => add()}>
                  添加一行
                </Button>
              </div>
              {fields.map(({ key, name, ...restField }) => (
                <Space key={key} style={{ display: 'flex' }} align="baseline">
                  <Form.Item {...restField} name={[name, 'personName']} className={styles['form-item']}>
                    <Input placeholder="请填写相关人员姓名" />
                  </Form.Item>
                  <Form.Item name={[name, 'rangeTime']}>
                    <RangePicker suffixIcon={<Icon src="/images/date.png" width={16} height={16} />} />
                  </Form.Item>
                  <Form.Item {...restField} name={[name, 'costTime']}>
                    <Input placeholder="请填写花费时间" suffix="h" onBlur={handleOnBlur} />
                  </Form.Item>
                  <Button
                    onClick={() => {
                      remove(name);
                      handleOnBlur();
                    }}
                  >
                    删除
                  </Button>
                </Space>
              ))}
            </>
          )}
        </Form.List>
      </Col>
    </>
  );
};

export default PlanItemBlock;
